//
//  ScenicViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ScenicViewController.h"
#import "ScenicListModel.h"
#import "ScenicListCell.h"
#import "ScenicDetailViewController.h"
#import "SDCycleScrollView.h"
#import "ScenicSearchViewController.h"


@interface ScenicViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *scenicDataArray;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UILabel *cityLable;
@property (nonatomic, strong) AppDelegate *app;
@property (nonatomic, strong) DDIndicator *indicator;

@end

@implementation ScenicViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
   [self addSubViews];
    self.view.backgroundColor = [UIColor whiteColor];
    [self freshHeader];
    [self addInternetObserver];
    
}

- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
    self.tableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpData)];
    [self.tableView.header beginRefreshing];
    } else {
        [self alertController];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
   // self.tabBarController.tabBar.hidden = NO;
//    self.navigationController.navigationBar.alpha = 0.5;
}

#pragma mark -- 解析数据
- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
  
    
    if (self.cityId == 0) {
        self.cityId = 144;
    }
    NSString *urlString = [NSString stringWithFormat:@"http://webapi.yilule.com:5580/api/TourData?pageSize=20&pageIndex=1&lat=40.030682&lng=116.343622&parentId=%ld&order=6", self.cityId];
    
    NSString *url = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    _scenicDataArray = [NSMutableArray array];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
        } else {
            NSArray *tempArr = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            
            for (NSDictionary *dic in tempArr) {
                ScenicListModel *model = [[ScenicListModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.scenicDataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.header endRefreshing];
                [self.indicator stopAnimating];
                [self.tableView reloadData];
                
            
            });
        }
    }];
    [dataTask resume];
    } else {
         [self.tableView.header endRefreshing];
        [self alertController];
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -- 布局

- (void)addSubViews
{
    [self setNavigationBar];
    [self addTableView];
  
}

- (void)setNavigationBar
{
    // navigationBar的背景图片
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"TestNaviBar1.jpg"] forBarMetrics:(UIBarMetricsDefault)];
    
    
    // 创建搜索按钮
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, -1, 240, 30)];
    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.delegate = self;
    self.searchBar .placeholder = @"请输入景点";
   
    self.searchBar.tintColor = [UIColor whiteColor];
    self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    // 创建一个View 给titleView赋值
    UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 240, 28)];
    // 把搜索框添加到view上
    [tempView addSubview:self.searchBar];
    tempView.layer.cornerRadius = 14;
    tempView.layer.masksToBounds = YES;
    self.navigationItem.titleView = tempView;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 50, 30);
    [button addTarget:self action:@selector(actionLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 20, 20)];
    imageV.image = [[UIImage imageNamed:@"TestCity.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    imageV.tintColor = [UIColor whiteColor];
    
    [button addSubview:imageV];
    
    self.cityLable = [[UILabel alloc] initWithFrame:CGRectMake(imageV.right, 0, 30, 30)];
    self.cityLable.text = @"三亚";
    self.cityLable.font = [UIFont systemFontOfSize:13];
    [button addSubview:self.cityLable];
    
//    [button setTitle:@"三亚" forState:(UIControlStateNormal)];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
     self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 113) style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        NSString *imageStr = [NSString stringWithFormat:@"SceniclunBo%d.jpg", i + 1];
        UIImage *image = [UIImage imageNamed:imageStr];
        [imageArray addObject:image];
    }

    
    SDCycleScrollView *scennicScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 210) imagesGroup:imageArray];
    scennicScrollView.autoScrollTimeInterval = 3;
    scennicScrollView.dotColor = [UIColor blueColor];
    scennicScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.tableView.tableHeaderView = scennicScrollView;
    
}


#pragma mark -- tableView的代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.scenicDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ScenicList";
    ScenicListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ScenicListCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.scenicDataArray.count > 0) {
        ScenicListModel *model = self.scenicDataArray[indexPath.row];
        cell.model = model;
       
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     ScenicListModel *model = self.scenicDataArray[indexPath.row];
    ScenicDetailViewController *sdVC = [[ScenicDetailViewController alloc] init];
     [self.tabBarController.tabBar setHidden:YES];
    sdVC.hidesBottomBarWhenPushed = YES;
    sdVC.imageUrl = model.NewPic;
    sdVC.sid = model.ID;
    [self.navigationController pushViewController:sdVC animated:YES];
    
}

#pragma mark -- 实现searchBar的代理方法
// 当开始编辑的时候 跳转到search页面
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    // 显示 取消按钮
    ScenicSearchViewController *ssVC = [[ScenicSearchViewController alloc] init];
    ssVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:ssVC animated:NO];
    return NO;
    
}// return NO to not become first responder


#pragma mark -- button的点击方法
- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    ScenicCityListViewController *scVC = [[ScenicCityListViewController alloc] init];
    scVC.delegate = self;
    scVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:scVC animated:YES];
}

#pragma mark -- 实现代理方法
- (void)reloadDatById:(NSInteger)Id cityName:(NSString *)cityName
{
    self.cityId = Id;
    self.cityLable.text = cityName;
    [self addLoading];
    [self setUpData];
}

#pragma mark -- 等待动画
- (void)addLoading
{
    // 添加等待动画
      self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake((kScreenWidth - 40) / 2, (kScreenHeight - 40) / 2, 40, 40)];
    [self.view addSubview:self.indicator];
    [self.indicator startAnimating];
    
}


// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
